<script setup>
import {useRoute} from "vue-router";
import {conDesignOptions, paramDataTypeOptions} from "@/mixins/index.js";
import {useTabsStore} from "@/store/index.js";
import {apiParam} from "@/utils/index.js";
import {uuid} from "@/utils/random.js";
import {skyMsgBox, skyMsgError, skyMsgWarning, skyNoticeError, skyNoticeSuccess} from "@/utils/sky.js";
import {standOpenWindowApi} from "@/apis/ADM/frmStandOpenWindows/index.js";

const route = useRoute();
const tabsStore = useTabsStore();
tabsStore.setTabTitle(`${route.meta.title}`);
const skyDialogCondRef = ref();
const skyDialogLieTouRef = ref();
const formRef = ref();
const formCondRef = ref();
const formLieTouRef = ref();
const activeName = ref('form');
const handleClick = (tab) => {
  tabsStore.value = tab.props.name;
};
const pageData = ref({
  title: "详情",
  form: {
    Caption: "",
    ReturnLst: "",
    Code: "",
    Seq: "",
    IsMultSelect: 0,
    ExpresSql: "",
    Remark: "",
    Columns: [],
    Conditions: [],
  },
  rules: {
    Caption: [{required: true, message: "请输入开窗名称", trigger: "blur"}],
    ReturnLst: [{required: true, message: "请输入开窗类别", trigger: "blur"}],
    Code: [{required: true, message: "请输入编码", trigger: "blur"}],
    Seq: [{required: true, message: "请输入序号", trigger: "blur"}],
  },
  formCond: {
    RecordId: uuid(),
    ConCaption: "",
    ConName: "",
    ConDesign: "like",
    ConDataType: "",
  },
  rulesCond: {
    ConCaption: [{required: true, message: "请输入标题", trigger: "blur"}],
    ConName: [{required: true, message: "请输入字段名", trigger: "blur"}],
    ConDesign: [{required: true, message: "请选择条件逻辑", trigger: "blur"}],
    ConDataType: [{required: true, message: "请选择数据类型", trigger: "blur"}],
  },
  formLieTou: {
    RecordId: uuid(),
    DisplayCaption: "",
    DisplayFieldName: "",
    DisplayWidth: 0,
  },
  rulesLieTou: {
    DisplayCaption: [{required: true, message: "请输入标题", trigger: "blur"}],
    DisplayFieldName: [{required: true, message: "请输入字段名", trigger: "blur"}],
  },
});
const method = reactive({
  /** 新增条件 */
  handleAddCond: () => {
    // 打开弹出框
    skyDialogCondRef.value.skyOpen();
    // 重置条件
    method.resetCond();
    // 标题
    pageData.value.title = "添加";
  },
  /** 删除条件 */
  handleDeleteCond: (row) => {
    const id = row.RecordId;
    if (id === null || id === "") {
      skyMsgWarning("请选中需要删除的数据🌻");
      return;
    }
    skyMsgBox("您确认需要删除参数名称[" + row.ConCaption + "]么？")
      .then(() => {
        try {
          const index = pageData.value.form.Conditions.find(item => item.RecordId === id);
          pageData.value.form.Conditions.splice(index, 1);
          skyNoticeSuccess("删除成功🌻");
        } catch (error) {
          skyNoticeError("删除失败，请刷新重试🌻");
        }
      })
      .catch(() => {
        skyMsgError("已取消🌻");
      });
  },
  /** 修改条件 */
  handleUpdateCond: (row) => {
    // 打开弹出框
    skyDialogCondRef.value.skyOpen();
    pageData.value.title = "修改";
    const id = row ? row.RecordId : "";
    if (id == null || id === "") {
      skyMsgError("请选中需要修改的数据🌻");
    }
    // 回显数据
    method.handleEchoCond(id);
  },
  /** 回显数据 */
  handleEchoCond: (id) => {
    if (id === null || id === "") {
      skyMsgWarning("请选择需要修改的数据🌻");
      return;
    }
    try {
      const cond = pageData.value.form.Conditions.find(item => item.RecordId === id);
      // 浅拷贝
      pageData.value.formCond = {...cond};
    } catch (error) {
      skyNoticeError("数据获取失败，请刷新重试🌻");
    }
  },
  /** 确定条件 */
  handleConfirmCond: () => {
    if (!formCondRef.value) return;
    (formCondRef.value).validate(async (valid) => {
      if (valid) {
        const flag = pageData.value.form.Conditions.some(item => item.RecordId === pageData.value.formCond.RecordId);
        if (flag) {
          try {
            const index = pageData.value.form.Conditions.findIndex(item => item.RecordId === pageData.value.formCond.RecordId);
            pageData.value.form.Conditions.splice(index, 1, {...pageData.value.formCond});
            skyDialogCondRef.value.skyQuickClose();
            method.resetCond();
          } catch (error) {
            skyNoticeError("修改失败失败，请刷新重试🌻");
          }
        } else {
          try {
            pageData.value.form.Conditions.push(pageData.value.formCond);
            skyDialogCondRef.value.skyQuickClose();
            method.resetCond();
          } catch (error) {
            skyNoticeError("添加失败，请刷新重试🌻");
          }
        }
      } else {
        skyMsgError("验证失败，请检查填写内容🌻");
        pageData.value.confirmLoading = false;
      }
    });
  },
  /** 取消条件 */
  handleCancelCond: () => {
    skyDialogCondRef.value.skyClose();
  },
  /** 清空表单条件 */
  resetCond: () => {
    nextTick(() => {
      if (formCondRef.value) {
        // 重置该表单项，将其值重置为初始值，并移除校验结果
        formCondRef.value.resetFields();
      }
    });
    pageData.value.formCond = {
      RecordId: uuid(),
      ConCaption: "",
      ConName: "",
      ConDesign: "like",
      ConDataType: "",
    };
  },
  /** 新增列头 */
  handleAddLieTou: () => {
    // 打开弹出框
    skyDialogLieTouRef.value.skyOpen();
    // 重置条件
    method.resetLieTou();
    // 标题
    pageData.value.title = "添加";
  },
  /** 删除列头 */
  handleDeleteLieTou: (row) => {
    const id = row.RecordId;
    if (id === null || id === "") {
      skyMsgWarning("请选中需要删除的数据🌻");
      return;
    }
    skyMsgBox("您确认需要删除参数名称[" + row.DisplayCaption + "]么？")
      .then(() => {
        try {
          const index = pageData.value.form.Columns.find(item => item.RecordId === id);
          pageData.value.form.Columns.splice(index, 1);
          skyNoticeSuccess("删除成功🌻");
        } catch (error) {
          skyNoticeError("删除失败，请刷新重试🌻");
        }
      })
      .catch(() => {
        skyMsgError("已取消🌻");
      });
  },
  /** 修改列头 */
  handleUpdateLieTou: (row) => {
    // 打开弹出框
    skyDialogLieTouRef.value.skyOpen();
    pageData.value.title = "修改";
    const id = row ? row.RecordId : "";
    if (id == null || id === "") {
      skyMsgError("请选中需要修改的数据🌻");
    }
    // 回显数据
    method.handleEchoLieTou(id);
  },
  /** 回显数据 */
  handleEchoLieTou: (id) => {
    if (id === null || id === "") {
      skyMsgWarning("请选择需要修改的数据🌻");
      return;
    }
    try {
      const cond = pageData.value.form.Columns.find(item => item.RecordId === id);
      // 浅拷贝
      pageData.value.formLieTou = {...cond};
    } catch (error) {
      skyNoticeError("数据获取失败，请刷新重试🌻");
    }
  },
  /** 确定条件 */
  handleConfirmLieTou: () => {
    if (!formLieTouRef.value) return;
    (formLieTouRef.value).validate(async (valid) => {
      if (valid) {
        const flag = pageData.value.form.Columns.some(item => item.RecordId === pageData.value.formLieTou.RecordId);
        if (flag) {
          try {
            const index = pageData.value.form.Columns.findIndex(item => item.RecordId === pageData.value.formLieTou.RecordId);
            pageData.value.form.Columns.splice(index, 1, {...pageData.value.formLieTou});
            skyDialogLieTouRef.value.skyQuickClose();
            method.resetLieTou();
          } catch (error) {
            skyNoticeError("修改失败失败，请刷新重试🌻");
          }
        } else {
          try {
            pageData.value.form.Columns.push(pageData.value.formLieTou);
            skyDialogLieTouRef.value.skyQuickClose();
            method.resetLieTou();
          } catch (error) {
            skyNoticeError("添加失败，请刷新重试🌻");
          }
        }
      } else {
        skyMsgError("验证失败，请检查填写内容🌻");
        pageData.value.confirmLoading = false;
      }
    });
  },
  /** 取消条件 */
  handleCancelLieTou: () => {
    skyDialogLieTouRef.value.skyClose();
  },
  /** 清空列头条件 */
  resetLieTou: () => {
    nextTick(() => {
      if (formLieTouRef.value) {
        // 重置该表单项，将其值重置为初始值，并移除校验结果
        formLieTouRef.value.resetFields();
      }
    });
    pageData.value.formLieTou = {
      RecordId: uuid(),
      DisplayCaption: "",
      DisplayFieldName: "",
      DisplayWidth: 0,
    };
  },
  /** 确定  */
  handleConfirm: () => {
    if (!formRef.value) return;
    (formRef.value).validate(async (valid) => {
      if (valid) {
        if (pageData.value.form.RecordId) {
          try {
            const data = apiParam("2.0", "SYS.StandOpenWindowsDAL.Update",
              [pageData.value.form]);
            await standOpenWindowApi(data);
            skyNoticeSuccess("修改成功🌻");
            method.handleCancel();
          } catch (error) {
            skyNoticeError("修改失败，请刷新重试🌻");
          }
        } else {
          try {
            const data = apiParam("2.0", "SYS.StandOpenWindowsDAL.Create",
              [pageData.value.form]);
            await standOpenWindowApi(data);
            skyNoticeSuccess("添加成功🌻");
            method.handleCancel();
          } catch (error) {
            pageData.value.confirmLoading = false;
            skyNoticeError("添加失败，请刷新重试🌻");
          }
        }
      } else {
        skyMsgError("验证失败，请检查填写内容🌻");
        pageData.value.confirmLoading = false;
      }
    });
  },
  /** 取消 */
  handleCancel: () => {
    if (route.meta?.isAffix) return;
    tabsStore.removeTab(route.fullPath);
  },
});
onMounted(async () => {
  const data = apiParam("2.0", "SYS.StandOpenWindowsDAL.GetById", [route.params.params]);
  const res = await standOpenWindowApi(data);
  if (!(res.data === null)) {
    pageData.value.form = res.data;
  } else {
    // 清空表单数据
    pageData.value.form = {
      Caption: "",
      ReturnLst: "",
      Code: "",
      Seq: "",
      IsMultSelect: 0,
      ExpresSql: "",
      Remark: "",
      Columns: [],
      Conditions: [],
    };
  }
});
</script>

<template>
  <div class="sky-flex">
    <SkyCard>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="基本信息" name="form">
          <el-form ref="formRef" :rules="pageData.rules" :model="pageData.form" label-width="auto" status-icon>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="开窗名称" prop="Caption">
                  <el-input v-model="pageData.form.Caption" placeholder="请输入开窗名称" clearable/>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="开窗类别" prop="ReturnLst">
                  <el-input v-model="pageData.form.ReturnLst" placeholder="请输入开窗类别" clearable/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="编码" prop="Code">
                  <el-input v-model="pageData.form.Code" placeholder="请输入编码" clearable/>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="序号" prop="Seq">
                  <el-input v-model="pageData.form.Seq" placeholder="请输入序号" clearable/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="是否多重选择" prop="IsMultSelect">
                  <el-radio-group v-model="pageData.form.IsMultSelect">
                    <el-radio :value="1">是</el-radio>
                    <el-radio :value="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }"></el-col>
            </el-row>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="SQL" prop="ExpresSql">
                  <el-input v-model="pageData.form.ExpresSql" :rows="5" type="textarea" placeholder="请输入SQL"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="备注" prop="Remark">
                  <el-input v-model="pageData.form.Remark" :rows="2" type="textarea" placeholder="请输入备注"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 10 }"></el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 2 }">
                <el-button type="primary" plain @click="method.handleConfirm">保存</el-button>
                <el-button type="danger" plain @click="method.handleCancel">取消</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="条件描述" name="condition">
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-button type="primary" icon="plus" plain @click="method.handleAddCond">新增条件</el-button>
            </el-col>
          </el-row>
          <br/>
          <el-table
            :height="600"
            :data="pageData.form.Conditions"
            empty-text="暂时没有数据哟🌻"
            border
          >
            <el-table-column label="标题" prop="ConCaption" align="center"/>
            <el-table-column label="字段名" prop="ConName" align="center"/>
            <el-table-column label="条件逻辑" prop="ConDesign" align="center">
              <template #default="scope">
                <SkyTag :tagOptions="conDesignOptions" :value="scope.row.ConDesign"></SkyTag>
              </template>
            </el-table-column>
            <el-table-column label="数据类型" prop="ConDataType" align="center">
              <template #default="scope">
                <SkyTag :tagOptions="paramDataTypeOptions" :value="scope.row.ConDataType"></SkyTag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120" fixed="right">
              <template #default="{ row }">
                <el-tooltip content="修改🌻" placement="top">
                  <el-button
                    type="primary"
                    icon="Edit"
                    circle
                    plain
                    @click="method.handleUpdateCond(row)"
                  ></el-button>
                </el-tooltip>
                <el-tooltip content="删除🌻" placement="top">
                  <el-button
                    type="danger"
                    icon="Delete"
                    circle
                    plain
                    @click="method.handleDeleteCond(row)"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <br/>
          <div class="flex">
            <el-button type="primary" plain @click="method.handleConfirm">保存</el-button>
            <el-button type="danger" plain @click="method.handleCancel()">取消</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="列头描述" name="lieTou">
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-button type="primary" icon="plus" plain @click="method.handleAddLieTou">新增列头</el-button>
            </el-col>
          </el-row>
          <br/>
          <el-table
            :height="600"
            :data="pageData.form.Columns"
            empty-text="暂时没有数据哟🌻"
            border
          >
            <el-table-column label="标题" prop="DisplayCaption" align="center"/>
            <el-table-column label="字段名" prop="DisplayFieldName" align="center"/>
            <el-table-column label="宽度" prop="DisplayWidth" align="center"/>
            <el-table-column label="操作" align="center" width="120" fixed="right">
              <template #default="{ row }">
                <el-tooltip content="修改🌻" placement="top">
                  <el-button
                    type="primary"
                    icon="Edit"
                    circle
                    plain
                    @click="method.handleUpdateLieTou(row)"
                  ></el-button>
                </el-tooltip>
                <el-tooltip content="删除🌻" placement="top">
                  <el-button
                    type="danger"
                    icon="Delete"
                    circle
                    plain
                    @click="method.handleDeleteLieTou(row)"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <br/>
          <div class="flex">
            <el-button type="primary" plain @click="method.handleConfirm">保存</el-button>
            <el-button type="danger" plain @click="method.handleCancel()">取消</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
      <!-- 条件 - 添加 OR 修改 -->
      <SkyDialog
        ref="skyDialogCondRef"
        :title="pageData.title"
        @skyConfirm="method.handleConfirmCond"
        @skyCancel="method.handleCancelCond"
        :width="600"
      >
        <template #content>
          <el-form ref="formCondRef" :rules="pageData.rulesCond" :model="pageData.formCond" label-width="auto" status-icon>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="标题" prop="ConCaption">
                  <el-input v-model="pageData.formCond.ConCaption" placeholder="请输入标题" clearable/>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="字段名" prop="ConName">
                  <el-input v-model="pageData.formCond.ConName" placeholder="请输入字段名" clearable/>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="条件逻辑" prop="ConDesign">
                  <el-select v-model="pageData.formCond.ConDesign" clearable>
                    <el-option
                      v-for="item in conDesignOptions"
                      :key="item.label"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="数据类型" prop="ConDataType">
                  <el-select v-model="pageData.formCond.ConDataType" clearable>
                    <el-option
                      v-for="item in paramDataTypeOptions"
                      :key="item.label"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </SkyDialog>
      <!-- 列头 - 添加 OR 修改 -->
      <SkyDialog
        ref="skyDialogLieTouRef"
        :title="pageData.title"
        @skyConfirm="method.handleConfirmLieTou"
        @skyCancel="method.handleCancelLieTou"
        :width="600"
      >
        <template #content>
          <el-form ref="formLieTouRef" :rules="pageData.rulesLieTou" :model="pageData.formLieTou" label-width="auto" status-icon>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="标题" prop="DisplayCaption">
                  <el-input v-model="pageData.formLieTou.DisplayCaption" placeholder="请输入标题" clearable/>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="字段名" prop="DisplayFieldName">
                  <el-input v-model="pageData.formLieTou.DisplayFieldName" placeholder="请输入字段名" clearable/>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="宽度" prop="DisplayWidth">
                  <el-input-number v-model="pageData.formLieTou.DisplayWidth" clearable/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </SkyDialog>
    </SkyCard>
  </div>
</template>

<style scoped lang="scss">
.flex {
  display: flex;
  justify-content: center;
}
</style>
